package com.yogee.topseller.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.SharedPreferencesUtils;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.MainActivity;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.base.HttpActivity;
import com.yogee.topseller.adapter.AllLabelAdapter;
import com.yogee.topseller.adapter.InterestLabelAdapter;
import com.yogee.topseller.application.TopellerApplication;
import com.yogee.topseller.bean.AddFastQueryBean;
import com.yogee.topseller.bean.ModifyFastQueryLabelBean;
import com.yogee.topseller.bean.ModifyNameBean;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.layout.UpdateNameFragment;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.view.FlowLayout;
import com.yogee.topseller.view.FlowLayoutFlashDetail;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @auathor ${XiaoJianghong}
 * @date 2017/7/16.
 */

public class FlashDetailsActivity extends HttpActivity implements FlowLayout.OnAddClickListener, FlowLayoutFlashDetail.OnDeleteClickListener, UpdateNameFragment.UpdateNameListener {

    @BindView(R.id.flash_details_defout_fl)
    FlowLayoutFlashDetail defoutFl;
    @BindView(R.id.flash_details_hot_lable_fl)
    FlowLayout hotLableFl;
    @BindView(R.id.flash_details_title_tv)
    EditText titleTv;
    @BindView(R.id.ll_flash_detail)
    LinearLayout ll_flash_detail;
    @BindView(R.id.rl_edit)
    RelativeLayout  rl_edit;
    @BindView(R.id.all_lable_rv)
    RecyclerView all_lable_rv;
    @BindView(R.id.tv_delete_btn)
    TextView tv_delete_btn;

    private AllLabelAdapter adapter;
    private List<AddFastQueryBean.LabelListBean> labelListBeen;
    private String flashId = "";
    private String name;
    private String edit_name="";
    private UpdateNameFragment fragment;
    private String labels;
    private List<AddFastQueryBean.FootListBeanNew> footList = new ArrayList<>();

    private PopupWindow popupWindow_createss;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_flash_details;
    }

    @Override
    protected void initView() {
        flashId = getIntent().getStringExtra("flashId");
        defoutFl.setOnDeleteClickListener(this);
        hotLableFl.setOnAddClickListener(this);
//        titleTv.setFocusable(false);
        titleTv.setFocusableInTouchMode(false);

        all_lable_rv.setLayoutManager(new LinearLayoutManager(this));
        all_lable_rv.setHasFixedSize(true);
        adapter = new AllLabelAdapter(this,this);
        all_lable_rv.setAdapter(adapter);
        addAllFastQueryPage(AppUtil.getUserId(this));

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @OnClick({R.id.flash_details_back_iv, R.id.flash_details_right_iv, R.id.flash_details_sure_rl, R.id.flash_details_search_ll, R.id.flash_details_allables_tv,R.id.tv_delete_btn,R.id.rl_edit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flash_details_back_iv://返回
                finish();
                break;
            case R.id.flash_details_right_iv:// 保存
//                fragment = new UpdateNameFragment();
//                fragment.show(getFragmentManager(), "");
//                fragment.setUpdateNameListener(this);
                edit_name = titleTv.getText().toString();
                if(edit_name.equals("")){
                    ToastUtils.showToast(FlashDetailsActivity.this,"名字不能为空");
                }else{
                    modifyFastQuery(AppUtil.getUserId(FlashDetailsActivity.this),labels, edit_name,flashId);
                }
                break;
            case R.id.flash_details_search_ll://搜索标签
                startActivityForResult(new Intent(this, TagSearchHActivity.class), 100);
                break;
            case R.id.flash_details_allables_tv://全部标签
                startActivityForResult(new Intent(this, FlashAllLableActivity.class).putExtra("flashId", flashId), 101);
                break;
            case R.id.flash_details_sure_rl://闪搜
                if(!AppUtil.isFastDoubleClick()){
                    if (labelListBeen.size() > 0){
                        // 如果是新增闪搜，先执行新增操作
                        if(flashId ==null||flashId.equals("")){
//                        ToastUtils.showToast(this, "这是新增");
                            HttpManager.getInstance().modifyFastQueryLabel(AppUtil.getUserId(FlashDetailsActivity.this), labels, titleTv.getText().toString(), flashId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ModifyFastQueryLabelBean>() {
                                @Override
                                public void onNext(ModifyFastQueryLabelBean o) {

                                    SharedPreferencesUtils.put(FlashDetailsActivity.this,SharedPreferencesUtils.HAVE_FLASH,true);
                                    FlashDetailsActivity.this.flashId = o.getQueryId();
                                    startActivity(new Intent(FlashDetailsActivity.this, BeginQueryActivity.class).putExtra("id", flashId));
                                    finish();
                                }
                            }, this));
                        }else{
                            edit_name = titleTv.getText().toString();
                            if(edit_name.equals("")){
                                ToastUtils.showToast(FlashDetailsActivity.this,"名字不能为空");
                            }else{
                                HttpManager.getInstance().modifyFastQueryLabel(AppUtil.getUserId(FlashDetailsActivity.this), labels, name, flashId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ModifyFastQueryLabelBean>() {
                                    @Override
                                    public void onNext(ModifyFastQueryLabelBean o) {

                                        SharedPreferencesUtils.put(FlashDetailsActivity.this,SharedPreferencesUtils.HAVE_FLASH,true);
                                        FlashDetailsActivity.this.flashId = o.getQueryId();
//                                    ToastUtils.showToast(FlashDetailsActivity.this,"修改成功");
                                        startAc(labels,edit_name,o.getQueryId());
//                adapter.addData(footList,labelListBeen);
//                addAllFastQueryPage(AppUtil.getUserId(FlashDetailsActivity.this));
                                    }
                                }, this));
                            }


                        }
                    } else
                        ToastUtils.showToast(this, "请选择标签");
                }

                break;
            // 删除分组
            case R.id.tv_delete_btn:
//                deleteFastQuery(flashId,"");
//                ToastUtils.showToast(FlashDetailsActivity.this,"开始删除");
                showdeletePop();
                break;
            case R.id.rl_edit:
//                fragment = new UpdateNameFragment();
//                fragment.show(getFragmentManager(), "");
//                fragment.setUpdateNameListener(this);
                titleTv.setFocusableInTouchMode(true);
                titleTv.requestFocus();
                titleTv.setSelection(titleTv.getText().toString().length());
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                rl_edit.setVisibility(View.GONE);
                break;

        }
    }

    private void startAc(String labels,String name,final String flashIds){
        HttpManager.getInstance().modifyFastQueryLabel(AppUtil.getUserId(FlashDetailsActivity.this), labels, name, flashIds).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ModifyFastQueryLabelBean>() {
            @Override
            public void onNext(ModifyFastQueryLabelBean o) {

                startActivity(new Intent(FlashDetailsActivity.this, BeginQueryActivity.class).putExtra("id", flashIds));
                finish();

            }
        }, this));
    }

    private void showdeletePop(){
        View popupWindowView = LayoutInflater.from(TopellerApplication.app).inflate(R.layout.pop_sure_or_cancel, null);
        int width = 0;

        popupWindow_createss = new PopupWindow(popupWindowView, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow_createss.setOutsideTouchable(true);


        TextView pop_sure_tv = (TextView) popupWindowView.findViewById(R.id.pop_sure_tv);
        TextView pop_cancel_tv = (TextView) popupWindowView.findViewById(R.id.pop_cancel_tv);
        pop_sure_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow_createss.dismiss();
                deleteFastQuery(flashId,"");
            }
        });
        pop_cancel_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow_createss.dismiss();
            }
        });
        popupWindow_createss.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
//                backgroundAlpha(1f);
            }
        });

//        popupWindow_createss.setBackgroundDrawable(new ColorDrawable(0x00000000));


        //菜单背景色
//        ColorDrawable dw = new ColorDrawable(0xffffffff);
//        popupWindow_createss.setBackgroundDrawable(dw);
        //显示位置
        popupWindow_createss.showAtLocation(ll_flash_detail, Gravity.CENTER, 0, -200);
//        backgroundAlpha(0.6f);

    }

    /**
     * 设置添加屏幕的背景透明度
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha)
    {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }



    @Override
    public void onDeleteClick(AddFastQueryBean.LabelListBean bean) {
        if (labelListBeen.contains(bean)) {
            labelListBeen.remove(bean);
            defoutFl.setDeleteDatas1(labelListBeen,FlashDetailsActivity.this);

            labels = "";
            if (labelListBeen.size() > 0)
                for (AddFastQueryBean.LabelListBean bean1 : labelListBeen) {
                    labels += "," + bean1.getId();
                }
            if (!labels.isEmpty()) {
                labels = labels.substring(1);
            }
            adapter.addData(footList,labelListBeen);
//            modifyFastQuery(AppUtil.getUserId(this), labels, name, flashId);
        }
    }

    @Override
    public void onAddClick(AddFastQueryBean.FootListBean bean) {
        if(labelListBeen.size()<5){
            AddFastQueryBean.LabelListBean ListBean = new AddFastQueryBean.LabelListBean();
            ListBean.setName(bean.getName());
            ListBean.setId(bean.getId());

            boolean isHas = false;

            for (int i = 0; i < labelListBeen.size(); i++) {
                if (labelListBeen.get(i).getId().equals(bean.getId())) {
                    isHas = true;
                    ToastUtils.showToast(FlashDetailsActivity.this, "标签已经存在");
                    break;
                }
            }
            if (!isHas) {
                labelListBeen.add(ListBean);
                defoutFl.setDeleteDatas1(labelListBeen,FlashDetailsActivity.this);
                labels = "";
                if (labelListBeen.size() > 0)
                    for (AddFastQueryBean.LabelListBean bean1 : labelListBeen) {
                        labels += "," + bean1.getId();
                    }
                labels = labels.substring(1);
//                modifyFastQuery(AppUtil.getUserId(this), labels, name, flashId);
            }
            adapter.addData(footList,labelListBeen);
        }else{
            ToastUtils.showToast(FlashDetailsActivity.this,"最多选择5个标签");
        }

    }

    @Override
    public void onUpdateNameCLick(String name) {//更新名字
//        modifyName(flashId, name);
        modifyFastQuery(AppUtil.getUserId(this), labels, name, flashId);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (null != data) {
            // 根据上面发送过去的请求吗来区别
            switch (requestCode) {
                case 100:
                    String id = data.getStringExtra("id");
                    String name = data.getStringExtra("name");
                    AddFastQueryBean.FootListBean bean = new AddFastQueryBean.FootListBean();
                    bean.setId(id);
                    bean.setName(name);
                    onAddClick(bean);
                    break;
                case 101:
                    flashId = data.getStringExtra("flashId");
//                    addAllFastQueryPage(AppUtil.getUserId(this));
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 添加闪搜
     *
     * @param userId
     */
    private void addAllFastQueryPage(String userId) {
        HttpManager.getInstance().addFastQueryPage(userId, "1", flashId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<AddFastQueryBean>() {
            @Override
            public void onNext(AddFastQueryBean o) {
                name = o.getName();
                titleTv.setText(o.getName());
                labelListBeen = o.getLabelList();
                defoutFl.setDeleteDatas1(o.getLabelList(),FlashDetailsActivity.this);
//                hotLableFl.setHotDatas(o.getFootList());

                footList = o.getFootList();
                adapter.addData(footList,labelListBeen);
                labels = "";
                if (labelListBeen.size() > 0) {
                    for (AddFastQueryBean.LabelListBean bean1 : labelListBeen) {
                        labels += "," + bean1.getId();
                    }
                    labels = labels.substring(1);
                }
            }
        }, this));
    }

//    /**
//     * 添加闪搜
//     *
//     * @param
//     */
//    private void addFastQueryPage(String userId) {
//        HttpManager.getInstance().addFastQueryPage(userId, "1", flashId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<AddFastQueryBean>() {
//            @Override
//            public void onNext(AddFastQueryBean o) {
//                name = o.getName();
//                titleTv.setText(o.getName());
//                labelListBeen = o.getLabelList();
//                defoutFl.cleanTag();
//                if (labelListBeen != null && labelListBeen.size() > 0)
//                    defoutFl.setDeleteDatas1(o.getLabelList(),FlashDetailsActivity.this);
//                hotLableFl.cleanTag();
//                if (o.getFootList() != null && o.getFootList().size() > 0)
//                    hotLableFl.setHotDatasShow(o.getFootList(),o.getLabelList());
//                labels = "";
//                if (labelListBeen.size() > 0) {
//                    for (AddFastQueryBean.LabelListBean bean1 : labelListBeen) {
//                        labels += "," + bean1.getId();
//                    }
//                    labels = labels.substring(1);
//                }
//            }
//        }, this));
//    }

    /**
     * 更改闪搜名字
     *
     * @param flashId
     * @param names
     */
    private void modifyName(String flashId, String names) {
        HttpManager.getInstance().modifyName(flashId, names).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ModifyNameBean>() {
            @Override
            public void onNext(ModifyNameBean o) {
                titleTv.setText(o.getName());
//                fragment.dismiss();
                name = o.getName();
                ToastUtils.showToast(FlashDetailsActivity.this,"修改成功");

            }
        }, this));
    }

    /**
     * 实时保存闪搜
     *
     * @param userId
     * @param labels
     * @param name
     * @param flashId
     */
    private void modifyFastQuery(String userId, final String labels, final String name, final String flashId) {
        HttpManager.getInstance().modifyFastQueryLabel(userId, labels, name, flashId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ModifyFastQueryLabelBean>() {
            @Override
            public void onNext(ModifyFastQueryLabelBean o) {

                SharedPreferencesUtils.put(FlashDetailsActivity.this,SharedPreferencesUtils.HAVE_FLASH,true);
                FlashDetailsActivity.this.flashId = o.getQueryId();
                ToastUtils.showToast(FlashDetailsActivity.this,"修改成功");
                rl_edit.setVisibility(View.VISIBLE);
                titleTv.setText(name);
                titleTv.setFocusable(false);
                titleTv.setFocusableInTouchMode(false);
                rl_edit.setVisibility(View.VISIBLE);
//                adapter.addData(footList,labelListBeen);
//                addAllFastQueryPage(AppUtil.getUserId(FlashDetailsActivity.this));
            }
        }, this));
    }

    /**
     * 删除闪搜分组
     * @param flashId
     * @param labels
     */
    private void deleteFastQuery(String flashId,String labels){
        HttpManager.getInstance().deleteFastQuery(flashId,labels).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ModifyFastQueryLabelBean>() {
            @Override
            public void onNext(ModifyFastQueryLabelBean o) {
                ToastUtils.showToast(FlashDetailsActivity.this,"删除成功");
                FlashDetailsActivity.this.finish();
            }
        }, this));
    }
}
